public class PercolationStats {

    private double mean = 0;
    private double stddev = 0;
    private double confidenceLo;
    private double confidenceHi;

    public PercolationStats(int N, int T) {
        if (N <= 0 || T <= 0)
            throw new IllegalArgumentException();
        double[] p = new double[T];
        for (int k = 0; k < T; k++) {
            Percolation percolation = new Percolation(N);
            int count = 0;
            while (!percolation.percolates()) {
                int i, j;
                do {
                    i = StdRandom.uniform(N) + 1;
                    j = StdRandom.uniform(N) + 1;
                }
                while (percolation.isOpen(i, j));
                percolation.open(i, j);
                count++;
            }
            p[k] = 1.0 * count / N / N;
        }
        for (int k = 0; k < T; k++) {
            mean += p[k] / T;
        }
        for (int k = 0; k < T; k++) {
            stddev += (p[k] - mean) * (p[k] - mean) / (T - 1);
        }
        stddev = Math.sqrt(stddev);
        confidenceLo = mean - 1.96 * stddev / Math.sqrt(T);
        confidenceHi = mean + 1.96 * stddev / Math.sqrt(T);

    }

    public double mean() {
        return mean;
    }

    public double stddev() {
        return stddev;
    }

    public double confidenceLo() {
        return confidenceLo;
    }

    public double confidenceHi() {
        return confidenceHi;
    }

    public static void main(String[] args) {
        int N = Integer.valueOf(args[0]);
        int T = Integer.valueOf(args[1]);
        PercolationStats stats = new PercolationStats(N, T);
        System.out.println("mean = \t" + stats.mean());
        System.out.println("stddev = \t" + stats.stddev());
        System.out.println("95% confidence interval = \t"
                + stats.confidenceHi() + ", " + stats.confidenceLo());
    }
}